﻿using BCCommon.Enums;
using BCCommon.Extensions;
using BCDto.Common.Payment.Payment;
using BCDto.Trading.SaleContract;
using BCService.Trading.SaleContract;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Text;

namespace BCService.Common.Payment.PaymentBusiness
{
    public class PaymentBusinessService: IPaymentBusinessService
    {
        private readonly IConfiguration _configuration;
        private readonly ISaleContractService _saleContractService;
        public PaymentBusinessService(IConfiguration configuration, ISaleContractService saleContractService)
        {
            _configuration = configuration;
            _saleContractService = saleContractService;
        }

        public string GetPaymentSubject(PaymentRequestDto requestDto, out decimal amount)
        {
            decimal returnAmount = 0;
            string subject = string.Format("{0}-{1}", requestDto.OrderType.GetDescriptionString(), requestDto.ReferenceNumber);
            switch (requestDto.OrderType) {
                case FlowType.Shopping:
                    {
                        var saleContract = this.GetSaleContractInfo(requestDto.ReferenceNumber);
                        subject = string.Format("{0}_购物_订单编号-{1}", _configuration["WebsiteTitle"], saleContract.SaleContractNo);
                        amount = saleContract.SaleAmount;
                    }
                    break;
                case FlowType.AgentRecharge:
                    {
                        subject = string.Format("{0}_充值_订单编号-{1}", _configuration["WebsiteTitle"], Guid.NewGuid().ToString());
                        amount = requestDto.Amount;
                    }
                    break;
                default:
                    amount = returnAmount;
                    break;
            }

            return subject;
        }

        /// <summary>
        /// 获取销售合同信息
        /// </summary>
        /// <param name="referenceNumber">销售订单编号</param>
        /// <returns></returns>
        private SaleContractDto GetSaleContractInfo(string referenceNumber)
        {
            if (!long.TryParse(referenceNumber, out long saleContractId))
            {
                throw new ArgumentException("此订单信息不正确!");
            }

            var saleContractDto = _saleContractService.Get(saleContractId);
            if (saleContractDto == null)
            {
                throw new ArgumentException("此订单信息不存在!");
            }

            return saleContractDto;
        }
    }
}
